//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//

package org.jeecg.modules.business.excelUtils;

import java.lang.reflect.Field;
import java.util.*;

import org.apache.commons.lang3.StringUtils;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFRichTextString;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFRichTextString;
import org.jeecgframework.poi.excel.annotation.ExcelTarget;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.jeecgframework.poi.excel.entity.params.ExcelExportEntity;
import org.jeecg.modules.business.excelUtils.ExcelExportBase;
import org.jeecgframework.poi.excel.export.styler.IExcelExportStyler;
import org.jeecgframework.poi.exception.excel.ExcelExportException;
import org.jeecgframework.poi.exception.excel.enums.ExcelExportEnum;
import org.jeecgframework.poi.util.PoiPublicUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ExcelExportServer extends ExcelExportBase {
    private static final Logger LOGGER = LoggerFactory.getLogger(ExcelExportServer.class);
    private int MAX_NUM = 60000;

    public ExcelExportServer() {
    }

    private int createHeaderAndTitle(ExportParams entity, Sheet sheet, Workbook workbook, List<ExcelExportEntity> excelParams ) {
        int rows = 0;
        int feildWidth = this.getFieldWidth(excelParams);
        if (entity.getTitle() != null) {
            rows += this.createHeaderRow(entity, sheet, workbook, feildWidth);
        }

        rows += this.createTitleRow(entity, sheet, workbook, rows, excelParams);
        sheet.createFreezePane(0, rows, 0, rows);
        return rows;
    }
    private int createHeaderAndTitleForSheetList(ExportParams entity, Sheet sheet, Workbook workbook, List<ExcelExportEntity> excelParams , int rows) {
        int feildWidth = this.getFieldWidth(excelParams);
        if (entity.getTitle() != null) {
            rows += this.createHeaderRowSheetList(entity, sheet, workbook, feildWidth , rows);
        }

        rows += this.createTitleRow(entity, sheet, workbook, rows, excelParams);
       // sheet.createFreezePane(0, rows, 0, rows);
        return rows;
    }
    public int createHeaderRowSheetList(ExportParams entity, Sheet sheet, Workbook workbook, int feildWidth , int rows) {
        Row row = sheet.createRow(rows);
        row.setHeight(entity.getTitleHeight());
        this.createStringCell(row, 0, entity.getTitle(), this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);

        for(int i = 1; i <= feildWidth; ++i) {
            this.createStringCell(row, i, "", this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);
        }

        try {
            sheet.addMergedRegion(new CellRangeAddress(rows, rows, 0, feildWidth));
        } catch (IllegalArgumentException var9) {
            LOGGER.error("合并单元格错误日志：" + var9.getMessage());
            var9.fillInStackTrace();
        }

        if (entity.getSecondTitle() == null) {
            return 1;
        } else {
            row = sheet.createRow(rows+1);
            row.setHeight(entity.getSecondTitleHeight());
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.LEFT);
            style.setVerticalAlignment(VerticalAlignment.CENTER);
            CellStyle style2 = workbook.createCellStyle();
            style2.setAlignment(HorizontalAlignment.CENTER);
            style2.setVerticalAlignment(VerticalAlignment.CENTER);
            CellStyle style3 = workbook.createCellStyle();
            style3.setAlignment(HorizontalAlignment.RIGHT);
            style3.setVerticalAlignment(VerticalAlignment.CENTER);
            // 固定格式
            List<String> slist = Arrays.asList(entity.getSecondTitle().split(",")) ;
            this.createStringCell(row, 0, slist.get(0), style, (ExcelExportEntity)null);
            this.createStringCell(row, 3, slist.get(1), style2, (ExcelExportEntity)null);
            this.createStringCell(row, 7, slist.get(2), style3, (ExcelExportEntity)null);

           /* for(int i = 1; i <= feildWidth; ++i) {
                this.createStringCell(row, i, "", this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);
            }
*/
            try {
                sheet.addMergedRegion(new CellRangeAddress(rows + 1, rows + 1, 0, 2));
                sheet.addMergedRegion(new CellRangeAddress(rows + 1, rows + 1, 3, 6));
                sheet.addMergedRegion(new CellRangeAddress(rows + 1, rows + 1, 7, feildWidth));
            } catch (IllegalArgumentException var8) {
                LOGGER.error("合并单元格错误日志：" + var8.getMessage());
                var8.fillInStackTrace();
            }

            return 2;
        }
    }
    public int createHeaderRow(ExportParams entity, Sheet sheet, Workbook workbook, int feildWidth ) {
        Row row = sheet.createRow(1);
        row.setHeight(entity.getTitleHeight());
        this.createStringCell(row, 0, entity.getTitle(), this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);

        for(int i = 1; i <= feildWidth; ++i) {
            this.createStringCell(row, i, "", this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);
        }

        try {
            sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, feildWidth));
        } catch (IllegalArgumentException var9) {
            LOGGER.error("合并单元格错误日志：" + var9.getMessage());
            var9.fillInStackTrace();
        }

        if (entity.getSecondTitle() == null) {
            return 1;
        } else {
            row = sheet.createRow(1);
            row.setHeight(entity.getSecondTitleHeight());
            CellStyle style = workbook.createCellStyle();
            style.setAlignment(HorizontalAlignment.RIGHT);
            this.createStringCell(row, 0, entity.getSecondTitle(), style, (ExcelExportEntity)null);

            for(int i = 1; i <= feildWidth; ++i) {
                this.createStringCell(row, i, "", this.getExcelExportStyler().getHeaderStyle(entity.getHeaderColor()), (ExcelExportEntity)null);
            }

            try {
                sheet.addMergedRegion(new CellRangeAddress(1, 1, 0, feildWidth));
            } catch (IllegalArgumentException var8) {
                LOGGER.error("合并单元格错误日志：" + var8.getMessage());
                var8.fillInStackTrace();
            }

            return 2;
        }
    }

    public void createSheetList(Workbook workbook, List<Map<String, Object>> datalist, String[] exportFields) {
        if(datalist.size() == 0) {
            throw new RuntimeException("MAP_LIST IS NULL");
        }
        // 只创建一次
        Sheet sheet = null;
        int index = 0 ;
        for(int j = 0; j < datalist.size(); ++j) {
            ExportParams entity = (ExportParams)((Map)datalist.get(j)).get("params") ;
            Class<?> pojoClass = (Class)((Map)datalist.get(j)).get("entity") ;
            Collection<?> dataSet = (Collection)((Map)datalist.get(j)).get("data") ;
            List<String> totalList = (List<String>) ((Map)datalist.get(j)).get("totalList");
            if (LOGGER.isDebugEnabled()) {
                LOGGER.debug("Excel export start ,class is {}", pojoClass);
                LOGGER.debug("Excel version is {}", entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
            }

            if (workbook != null && entity != null && pojoClass != null && dataSet != null) {

                if(j == 0) {
                    super.type = entity.getType();
                    if (this.type.equals(ExcelType.XSSF)) {
                        this.MAX_NUM = 1000000;
                    }
                    try {
                        sheet = workbook.createSheet(entity.getSheetName());
                    } catch (Exception var19) {
                        sheet = workbook.createSheet();
                    }
                }
                try {
                    this.dataHanlder = entity.getDataHanlder();
                    if (this.dataHanlder != null) {
                        this.needHanlderList = Arrays.asList(this.dataHanlder.getNeedHandlerFields());
                    }

                    this.setExcelExportStyler((IExcelExportStyler)entity.getStyle().getConstructor(Workbook.class).newInstance(workbook));
                    Drawing patriarch = sheet.createDrawingPatriarch();
                    List<ExcelExportEntity> excelParams = new ArrayList();
                    if (entity.isAddIndex()) {
                        excelParams.add(this.indexExcelEntity(entity));
                    }

                    Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
                    if (exportFields != null) {
                        List<Field> list = new ArrayList(Arrays.asList(fileds));

                        for(int i = 0; i < list.size(); ++i) {
                            if (!Arrays.asList(exportFields).contains(((Field)list.get(i)).getName())) {
                                list.remove(i);
                                --i;
                            }
                        }

                        if (list != null && list.size() > 0) {
                            fileds = (Field[])list.toArray(new Field[0]);
                        } else {
                            fileds = null;
                        }
                    }

                    ExcelTarget etarget = (ExcelTarget)pojoClass.getAnnotation(ExcelTarget.class);
                    String targetId = etarget == null ? null : etarget.value();
                    this.getAllExcelField(entity.getExclusions(), targetId, fileds, excelParams, pojoClass, (List)null);
                    this.reConfigExcelExportParams(excelParams, entity);
                    index = entity.isCreateHeadRows() ? this.createHeaderAndTitleForSheetList(entity, sheet, workbook, excelParams , index == 0 ? 0 : index + 1) : 0;
                    this.setCellWith(excelParams, sheet);
                    this.setColumnHidden(excelParams, sheet);
                    short rowHeight = this.getRowHeight(excelParams);
                    this.setCurrentIndex(1);
                    Iterator<?> its = dataSet.iterator();
                    ArrayList tempList = new ArrayList();
                    while(its.hasNext()) {
                        Object t = its.next();
                        index += this.createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight);
                        tempList.add(t);
                        if (index >= this.MAX_NUM) {
                            break;
                        }
                    }

                    this.mergeCells(sheet, excelParams, index);
                    if (entity.getFreezeCol() != 0) {
                        sheet.createFreezePane(entity.getFreezeCol(), 0, entity.getFreezeCol(), 0);
                    }

                    its = dataSet.iterator();
                    int i = 0;

                    for(int le = tempList.size(); i < le; ++i) {
                        its.next();
                        its.remove();
                    }
                    // 添加统计数据
                   // index += this.addTotalData(totalList ,entity , sheet ,workbook,index);
                    index += this.addStatisticsRowForSheet(entity, workbook ,sheet);
                    if (dataSet.size() > 0) {
                        this.createSheetList(workbook, datalist, exportFields);
                    }

                } catch (Exception var20) {
                    LOGGER.error(var20.getMessage(), var20);
                    throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var20.getCause());
                }
            } else {
                throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
            }
        }

    }


    /**
     * 添加合计数据
     * @param totalList
     * @param rows
     * @return
     */
    private int addTotalData(List<String> totalList, ExportParams entity , Sheet sheet , Workbook workbook, int rows) {
        Row row = sheet.createRow(rows);
        row.setHeight(entity.getSecondTitleHeight());
        CellStyle style = workbook.createCellStyle();
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        row.setHeight(entity.getTitleHeight());
        if(style != null ){
            style.setBorderBottom(BorderStyle.THIN); //下边框
            style.setBorderLeft(BorderStyle.THIN);//左边框
            style.setBorderTop(BorderStyle.THIN);//上边框
            style.setBorderRight(BorderStyle.THIN);//右边框
        }
        for(int i = 0; i <= 10; ++i) {
            // 固定格式
            if(i == 6){
                this.createStringCell(row, 6, "合计", style, (ExcelExportEntity)null);
            }else if(i == 7){
                this.createStringCell(row, 7, totalList.get(0), style, (ExcelExportEntity)null);
            }else if(i == 9){
                this.createStringCell(row, 9, totalList.get(1), style, (ExcelExportEntity)null);
            } else if(i == 10){
                this.createStringCell(row, 10, totalList.get(2), style, (ExcelExportEntity)null);
            }else {
                this.createStringCell(row, i, "", style, (ExcelExportEntity)null);
            }
        }

        return 1 ;

    }
    public void createSheet(Workbook workbook, ExportParams entity, Class<?> pojoClass, Collection<?> dataSet, String[] exportFields) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Excel export start ,class is {}", pojoClass);
            LOGGER.debug("Excel version is {}", entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
        }

        if (workbook != null && entity != null && pojoClass != null && dataSet != null) {
            super.type = entity.getType();
            if (this.type.equals(ExcelType.XSSF)) {
                this.MAX_NUM = 1000000;
            }

            Sheet sheet = null;

            try {
                sheet = workbook.createSheet(entity.getSheetName());
            } catch (Exception var19) {
                sheet = workbook.createSheet();
            }

            try {
                this.dataHanlder = entity.getDataHanlder();
                if (this.dataHanlder != null) {
                    this.needHanlderList = Arrays.asList(this.dataHanlder.getNeedHandlerFields());
                }

                this.setExcelExportStyler((IExcelExportStyler)entity.getStyle().getConstructor(Workbook.class).newInstance(workbook));
                Drawing patriarch = sheet.createDrawingPatriarch();
                List<ExcelExportEntity> excelParams = new ArrayList();
                if (entity.isAddIndex()) {
                    excelParams.add(this.indexExcelEntity(entity));
                }

                Field[] fileds = PoiPublicUtil.getClassFields(pojoClass);
                if (exportFields != null) {
                    List<Field> list = new ArrayList(Arrays.asList(fileds));

                    for(int i = 0; i < list.size(); ++i) {
                        if (!Arrays.asList(exportFields).contains(((Field)list.get(i)).getName())) {
                            list.remove(i);
                            --i;
                        }
                    }

                    if (list != null && list.size() > 0) {
                        fileds = (Field[])list.toArray(new Field[0]);
                    } else {
                        fileds = null;
                    }
                }

                ExcelTarget etarget = (ExcelTarget)pojoClass.getAnnotation(ExcelTarget.class);
                String targetId = etarget == null ? null : etarget.value();
                this.getAllExcelField(entity.getExclusions(), targetId, fileds, excelParams, pojoClass, (List)null);
                this.reConfigExcelExportParams(excelParams, entity);
                int index = entity.isCreateHeadRows() ? this.createHeaderAndTitle(entity, sheet, workbook, excelParams) : 0;
                this.setCellWith(excelParams, sheet);
                this.setColumnHidden(excelParams, sheet);
                short rowHeight = this.getRowHeight(excelParams);
                this.setCurrentIndex(1);
                Iterator<?> its = dataSet.iterator();
                ArrayList tempList = new ArrayList();

                while(its.hasNext()) {
                    Object t = its.next();
                    index += this.createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight);
                    tempList.add(t);
                    if (index >= this.MAX_NUM) {
                        break;
                    }
                }

                this.mergeCells(sheet, excelParams, index);
                if (entity.getFreezeCol() != 0) {
                    sheet.createFreezePane(entity.getFreezeCol(), 0, entity.getFreezeCol(), 0);
                }

                its = dataSet.iterator();
                int i = 0;

                for(int le = tempList.size(); i < le; ++i) {
                    its.next();
                    its.remove();
                }

                this.addStatisticsRow(this.getExcelExportStyler().getStyles(true, (ExcelExportEntity)null), sheet);
                if (dataSet.size() > 0) {
                    this.createSheet(workbook, entity, pojoClass, dataSet, exportFields);
                }

            } catch (Exception var20) {
                LOGGER.error(var20.getMessage(), var20);
                throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var20.getCause());
            }
        } else {
            throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
        }
    }

    public void createSheetForMap(Workbook workbook, ExportParams entity, List<ExcelExportEntity> entityList, Collection<? extends Map<?, ?>> dataSet) {
        if (LOGGER.isDebugEnabled()) {
            LOGGER.debug("Excel version is {}", entity.getType().equals(ExcelType.HSSF) ? "03" : "07");
        }

        if (workbook != null && entity != null && entityList != null && dataSet != null) {
            super.type = entity.getType();
            if (this.type.equals(ExcelType.XSSF)) {
                this.MAX_NUM = 1000000;
            }

            Sheet sheet = null;

            try {
                sheet = workbook.createSheet(entity.getSheetName());
            } catch (Exception var15) {
                sheet = workbook.createSheet();
            }

            try {
                this.dataHanlder = entity.getDataHanlder();
                if (this.dataHanlder != null) {
                    this.needHanlderList = Arrays.asList(this.dataHanlder.getNeedHandlerFields());
                }

                this.setExcelExportStyler((IExcelExportStyler)entity.getStyle().getConstructor(Workbook.class).newInstance(workbook));
                Drawing patriarch = sheet.createDrawingPatriarch();
                List<ExcelExportEntity> excelParams = new ArrayList();
                if (entity.isAddIndex()) {
                    excelParams.add(this.indexExcelEntity(entity));
                }

                excelParams.addAll(entityList);
                this.sortAllParams(excelParams);
                int index = entity.isCreateHeadRows() ? this.createHeaderAndTitle(entity, sheet, workbook, excelParams) : 0;
                this.setCellWith(excelParams, sheet);
                this.setColumnHidden(excelParams, sheet);
                short rowHeight = this.getRowHeight(excelParams);
                this.setCurrentIndex(1);
                Iterator<?> its = dataSet.iterator();
                ArrayList tempList = new ArrayList();

                while(its.hasNext()) {
                    Object t = its.next();
                    index += this.createCells(patriarch, index, t, excelParams, sheet, workbook, rowHeight);
                    tempList.add(t);
                    if (index >= this.MAX_NUM) {
                        break;
                    }
                }

                if (entity.getFreezeCol() != 0) {
                    sheet.createFreezePane(entity.getFreezeCol(), 0, entity.getFreezeCol(), 0);
                }

                this.mergeCells(sheet, excelParams, index);
                its = dataSet.iterator();
                int i = 0;

                for(int le = tempList.size(); i < le; ++i) {
                    its.next();
                    its.remove();
                }

                if (dataSet.size() > 0) {
                    this.createSheetForMap(workbook, entity, entityList, dataSet);
                }

            } catch (Exception var16) {
                LOGGER.error(var16.getMessage(), var16);
                throw new ExcelExportException(ExcelExportEnum.EXPORT_ERROR, var16.getCause());
            }
        } else {
            throw new ExcelExportException(ExcelExportEnum.PARAMETER_ERROR);
        }
    }

    private int createTitleRow(ExportParams title, Sheet sheet, Workbook workbook, int index, List<ExcelExportEntity> excelParams) {
        Row row = sheet.createRow(index);
        int rows = this.getRowNums(excelParams);
        row.setHeight((short)450);
        Row listRow = null;
        if (rows == 2) {
            listRow = sheet.createRow(index + 1);
            listRow.setHeight((short)450);
        }

        int cellIndex = 0;
        CellStyle titleStyle = this.getExcelExportStyler().getTitleStyle(title.getColor());
        Font font = workbook.createFont() ;
        font.setBold(true);
        if(titleStyle != null ){
            titleStyle.setBorderBottom(BorderStyle.THIN); //下边框
            titleStyle.setBorderLeft(BorderStyle.THIN);//左边框
            titleStyle.setBorderTop(BorderStyle.THIN);//上边框
            titleStyle.setBorderRight(BorderStyle.THIN);//右边框
            titleStyle.setFont(font);
        }
        int i = 0;

        for(int exportFieldTitleSize = excelParams.size(); i < exportFieldTitleSize; ++i) {
            ExcelExportEntity entity = (ExcelExportEntity)excelParams.get(i);
            List sTitel;
            if (entity.isColspan()) {
                sTitel = entity.getSubColumnList();
                if (sTitel == null || sTitel.size() == 0) {
                    continue;
                }

                entity.initSubExportEntity(excelParams);
            }

            if (StringUtils.isNotBlank(entity.getName())) {
                this.createStringCell(row, cellIndex, entity.getName(), titleStyle, entity);
            }

            if (entity.getList() != null) {
                sTitel = entity.getList();
                if (StringUtils.isNotBlank(entity.getName())) {
                    try {
                        sheet.addMergedRegion(new CellRangeAddress(index, index, cellIndex, cellIndex + sTitel.size() - 1));
                    } catch (IllegalArgumentException var18) {
                        LOGGER.error("合并单元格错误日志：" + var18.getMessage());
                        var18.fillInStackTrace();
                    }
                }

                int j = 0;

                for(int size = sTitel.size(); j < size; ++j) {
                    this.createStringCell(rows == 2 ? listRow : row, cellIndex, ((ExcelExportEntity)sTitel.get(j)).getName(), titleStyle, entity);
                    ++cellIndex;
                }

                --cellIndex;
            } else if (rows == 2) {
                this.createStringCell(listRow, cellIndex, "", titleStyle, entity);

                try {
                    sheet.addMergedRegion(new CellRangeAddress(index, index + 1, cellIndex, cellIndex));
                } catch (IllegalArgumentException var17) {
                    LOGGER.error("合并单元格错误日志：" + var17.getMessage());
                    var17.fillInStackTrace();
                }
            }

            ++cellIndex;
        }

        return rows;
    }

    private int getRowNums(List<ExcelExportEntity> excelParams) {
        for(int i = 0; i < excelParams.size(); ++i) {
            ExcelExportEntity temp = (ExcelExportEntity)excelParams.get(i);
            if ((temp.getList() != null || temp.isColspan()) && StringUtils.isNotBlank(temp.getName())) {
                return 2;
            }
        }

        return 1;
    }

    private ExcelExportEntity indexExcelEntity(ExportParams entity) {
        ExcelExportEntity exportEntity = new ExcelExportEntity();
        exportEntity.setOrderNum(0);
        exportEntity.setName(entity.getIndexName());
        exportEntity.setWidth(10.0D);
        exportEntity.setFormat("isAddIndex");
        return exportEntity;
    }
}
